/*  Deadlock.c - detect potential deadlock */

#include <stdio.h>
typedef    enum { False=0, True=1 } bool ;

#define P 4
#define R 5

int reQuest[P][R] = {
                     {0,1,0,0,1},
                     {0,0,1,0,1},
                     {0,0,0,0,1},
                     {1,0,1,0,1}
                    };

int Usage[P][R] =   {
                     {1,0,1,1,0},
                     {1,1,1,1,0},
                     {0,0,0,1,0},
                     {0,0,0,0,0}
                    };

int Resource[R] =    {2,1,1,2,1};
int Available[R] =   {0,0,0,0,1};

bool greater(int X[],int Y[]) {
    for(int j=0;j<R;j++) if(X[j]>Y[j]) return True ;
    return False ;
}

#define copy(X,Y)  for(int j=0;j<R;j++) X[j]=Y[j];
#define add(X,Y)   for(int j=0;j<R;j++) X[j]=X[j]+Y[j];
#define pr(s,X)    printf("%s=\t",s); for(int j=0;j<R;j++) printf("%d",X[j]); printf("\n");

int main() {
    int Temp[R], Zero[R] = {0};
    pr("Z",Zero);
    copy(Temp,Available);
    pr("T",Temp);
    for(int p=0; p<P; p++) {
        pr("U[p]",Usage[p]);
        if(greater(Usage[p],Zero)) {
            pr("Q[p]",reQuest[p]);
            pr("T",Temp);
            if(greater(reQuest[p],Temp)){
                printf("deadlock %d\n",p);
            } else {
                printf("no deadlock %d\n",p);
                add(Temp,Usage[p]);
                pr("T",Temp);
            }
        } else {
            printf("no deadlock %d\n",p);
        }
    }
    return 0;
}
